<template>
  <div class="category-detail-finance">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon size="28" class="header-icon">
          <component :is="category.icon || 'Coin'"/>
        </el-icon>
        <h2>{{ category.name }}消费记录</h2>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRecord">
          <el-icon>
            <Plus/>
          </el-icon>
          添加记录
        </el-button>
        <el-button @click="exportData">
          <el-icon>
            <Download/>
          </el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="12" :sm="6" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon>
                <Money/>
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatAmount(overviewData.totalAmount) }}</div>
              <div class="stat-label">总支出</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon count">
              <el-icon>
                <Document/>
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.recordCount }}</div>
              <div class="stat-label">记录数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon average">
              <el-icon>
                <DataAnalysis/>
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatAmount(overviewData.averageAmount) }}</div>
              <div class="stat-label">平均金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon max">
              <el-icon>
                <TrendCharts/>
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatAmount(overviewData.maxAmount) }}</div>
              <div class="stat-label">最大支出</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="table-header">
          <span>{{ category.name }}消费记录列表</span>
          <div class="table-actions">
            <span class="total-text">总计: ¥{{ formatAmount(totalAmount) }}</span>
          </div>
        </div>
      </template>
      <el-table
          :data="recordsPageData"
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="date" label="日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.consumptionDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ formatAmount(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentMethodTagType(row.paymentMethod)" size="small">
              {{ getPaymentMethodText(row.paymentMethod) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isNecessary" label="必要" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isNecessary ? 'success' : 'info'" size="small">
              {{ getIsNecessaryText(row.isNecessary) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isStatistics" label="纳入统计" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isStatistics ? 'success' : 'warning'" size="small">
              {{ getIsStatisticsText(row.isStatistics) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </el-card>

    <!-- 图表分析 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :sm="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span>近7日支出趋势</span>
          </template>
          <div ref="trendChart" style="height: 300px; position: relative;">
            <div v-if="!recordsData || recordsData.length === 0" class="no-data-tip">
              暂无数据统计
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12">
        <el-card shadow="never" class="chart-card">
          <template #header>
            <span>支付方式分布</span>
          </template>
          <div ref="paymentMethodChart" style="height: 300px; position: relative;">
            <div v-if="!recordsData || recordsData.length === 0" class="no-data-tip">
              暂无数据统计
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 月度对比 -->
    <el-card shadow="never" class="chart-card">
      <template #header>
        <span>近6个月支出</span>
      </template>
      <div ref="monthlyChart" style="height: 350px; position: relative;">
        <div v-if="!recordsData || recordsData.length === 0" class="no-data-tip">
          暂无数据统计
        </div>
      </div>
    </el-card>
  </div>

  <AddRecordDialog
      v-model="addDialogVisible"
      :category="category"
      @confirm="handleConfirmAdd"
      @close="handleCancelAdd"
  />

  <UpdateRecordDialog
      v-model="updateDialogVisible"
      :category="category"
      :record="record"
      @confirm="handleConfirmUpdate"
      @close="handleCancelUpdate"
  />
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted, nextTick, computed, watch} from 'vue'
import * as echarts from 'echarts'
import {DataAnalysis, Document, Money, Plus, Download, TrendCharts} from '@element-plus/icons-vue'
import {consumptionRecordPersonalApi} from '@/api/consumptionRecordPersonal.js'
import {useUserStore} from "@/stores/user.js";
import {ElMessage,ElMessageBox } from "element-plus";
import AddRecordDialog from "@/components/common/AddRecordDialog.vue";
import UpdateRecordDialog from "@/components/common/UpdateRecordDialog.vue";

const userStore = useUserStore();
const props = defineProps({
  category: {
    type: Object,
    required: true
  }
})

// 图表引用
const trendChart = ref(null)
const paymentMethodChart = ref(null)
const monthlyChart = ref(null)

// 图表实例管理
const chartInstances = {
  trend: null,
  payment: null,
  monthly: null
}

// 响应式数据
const loading = ref(false)
const recordsPageData = ref([])
const recordsData = ref([])
const record = ref(null)
const overviewData = reactive({
  totalAmount: 0,
  recordCount: 0,
  averageAmount: 0,
  maxAmount: 0
})
const addDialogVisible = ref(false)
const updateDialogVisible = ref(false)
// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
// 标签类型映射
const getPaymentMethodTagType = (method) => {
  const map = {
    0: 'success',    // 微信
    1: 'primary',    // 支付宝
    2: 'info',       // 储蓄卡
    3: 'warning',    // 信用卡
    4: 'default'     // 其他
  }
  return map[method] || 'default'
}
// 支付方式文本转换
const getPaymentMethodText = (method) => {
  const map = {
    0: '微信',
    1: '支付宝',
    2: '储蓄卡',
    3: '信用卡',
    4: '其他'
  }
  return map[method] || '未知'
}
// 是否必要文本转换
const getIsNecessaryText = (isNecessary) => {
  return isNecessary ? '必要' : '非必要'
}
// 是否纳入统计文本转换
const getIsStatisticsText = (isStatistics) => {
  return isStatistics ? '纳入' : '不纳入'
}
// 监听分类变化
watch(() => props.category, async (newCategory) => {
  if (!newCategory) return

  // 重置数据
  resetData()

  // 清理图表实例
  cleanupCharts()

  // 获取数据
  await fetchAllData()
}, { deep: true })
// 获取所有数据
const fetchAllData = async () => {
  await Promise.all([
    fetchDataByCategory(1),
    fetchAllRecordsByCategoryAndUserId()
  ])
  updateOverviewData()
  initCharts()
}
// 根据分类ID和用户名获取数据(分页)
const fetchDataByCategory = async (pageNum = 1) => {
  loading.value = true
  try {
    const userid = userStore.userInfo?.id || -1
    const response = await consumptionRecordPersonalApi.page(
        props.category.id,
        userid,
        pageNum,
        pagination.pageSize
    )

    if (response.code === 200) {
      recordsPageData.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.pageNum = response.data.pageNum || pageNum
    } else {
      ElMessage.error(response.message || '获取消费记录失败')
    }
  } catch (error) {
    ElMessage.error('获取消费记录失败')
  } finally {
    loading.value = false
  }
}
// 查询当前分类下个人的所有消费记录
const fetchAllRecordsByCategoryAndUserId = async () => {
  try {
    const userid = userStore.userInfo?.id || -1
    const response = await consumptionRecordPersonalApi.all(
        props.category.id,
        userid
    )
    if (response.code === 200) {
      recordsData.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取消费记录失败')
    }
  } catch (error) {
    ElMessage.error('获取消费记录失败')
  }
}
// 更新概览数据
const updateOverviewData = () => {
  if (!recordsData.value.length) return

  overviewData.totalAmount = recordsData.value.reduce((sum, item) => sum + item.amount, 0)
  overviewData.recordCount = pagination.total || 0
  overviewData.averageAmount = overviewData.recordCount > 0 ? overviewData.totalAmount / overviewData.recordCount : 0
  overviewData.maxAmount = Math.max(...recordsData.value.map(item => item.amount))
}
// 重置数据
const resetData = () => {
  recordsPageData.value = []
  recordsData.value = []

  Object.assign(overviewData, {
    totalAmount: 0,
    recordCount: 0,
    averageAmount: 0,
    maxAmount: 0
  })

  pagination.pageNum = 1
}
// 清理图表实例
const cleanupCharts = () => {
  Object.keys(chartInstances).forEach(key => {
    if (chartInstances[key]) {
      chartInstances[key].dispose()
      chartInstances[key] = null
    }
  })
}
// 计算属性
const totalAmount = computed(() => {
  return recordsPageData.value.reduce((sum, item) => sum + item.amount, 0)
})
// 格式化函数
const formatAmount = (amount) => {
  return Number(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''

  if (dateString.includes('T')) {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  return new Date(dateString).toLocaleDateString('zh-CN')
}
// 分页事件处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchDataByCategory(1)
}
// 当前页码变更处理
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchDataByCategory(page)
}
// 记录操作函数
const handleAddRecord = () => {
  addDialogVisible.value = true
}
// 确认添加
const handleConfirmAdd = async (formData) => {
  try {
    const userid = userStore.userInfo?.id || -1
    const requestData = {
      typeId: formData.typeId,
      userId: userid,
      consumptionDate: formData.date,
      amount: formData.amount,
      paymentMethod: formData.paymentMethod,
      isNecessary: formData.isNecessary,
      isStatistics: formData.isStatistics,
      description: formData.description,
    }

    const response = await consumptionRecordPersonalApi.append(requestData)

    if (response.code === 200) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      await refreshData()
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加记录失败')
  }
}
// 添加取消
const handleCancelAdd = () => {
  addDialogVisible.value = false
}
// 修改
const handleEdit = (row) => {
  updateDialogVisible.value = true
  record.value = { ...row }
}
// 确认修改
const handleConfirmUpdate = async (formData) => {
  try {
    const userid = userStore.userInfo?.id || -1
    const submitData = {
      id: record.value.id,
      typeId: formData.typeId,
      userId: userid,
      consumptionDate: formData.date,
      amount: formData.amount,
      paymentMethod: formData.paymentMethod,
      isNecessary: formData.isNecessary,
      isStatistics: formData.isStatistics,
      description: formData.description,
    }

    const response = await consumptionRecordPersonalApi.update(submitData)

    if (response.code === 200) {
      ElMessage.success('修改成功')
      updateDialogVisible.value = false
      await refreshData()
    } else {
      ElMessage.error(response.message || '修改失败')
    }
  } catch (error) {
    ElMessage.error('修改记录失败')
  }
}
// 取消修改
const handleCancelUpdate = () => {
  updateDialogVisible.value = false
}
// 删除弹窗
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await handleDeleteConfirm(row)
  } catch {
    ElMessage.warning('已取消删除')
  }
}
// 确认删除
const handleDeleteConfirm = async (row) => {
  const response = await consumptionRecordPersonalApi.remove(row.id)
  if (response.code === 200) {
    ElMessage.success('删除成功')
    await refreshData()
  } else {
    ElMessage.error(response.message || '删除失败')
  }
}
// 刷新数据
const refreshData = async () => {
  await Promise.all([
    fetchDataByCategory(pagination.pageNum),
    fetchAllRecordsByCategoryAndUserId()
  ])
  updateOverviewData()
}

// 图表初始化
const initCharts = () => {
  nextTick(() => {
    initializeTrendChart()
    initializePaymentMethodChart()
    initializeMonthlyChart()
  })
}
// 图表数据生成函数
const generateTrendData = () => {
  if (!recordsData.value?.length) return { dates: [], amounts: [] }

  const dates = []
  const amounts = []

  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    dates.push(`${date.getMonth() + 1}-${date.getDate()}`)

    const dayRecords = recordsData.value.filter(record =>
        record.consumptionDate.startsWith(dateStr)
    )

    const dayTotal = dayRecords.reduce((sum, record) => sum + record.amount, 0)
    amounts.push(parseFloat(dayTotal.toFixed(2)))
  }

  return { dates, amounts }
}
// 支付方式数据生成函数
const generatePaymentMethodData = () => {
  if (!recordsData.value?.length) return []

  const paymentStats = {}
  recordsData.value.forEach(record => {
    const methodText = getPaymentMethodText(record.paymentMethod)
    paymentStats[methodText] = (paymentStats[methodText] || 0) + record.amount
  })

  return Object.keys(paymentStats).map(method => ({
    name: method,
    value: parseFloat(paymentStats[method].toFixed(2))
  }))
}
// 月度数据生成函数
const generateMonthlyData = () => {
  if (!recordsData.value?.length) return { months: [], currentMonth: [] }

  const months = []
  const currentMonth = []
  const now = new Date()
  const currentMonthIndex = now.getMonth()
  const currentYear = now.getFullYear()
  const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']

  for (let i = 5; i >= 0; i--) {
    const date = new Date(currentYear, currentMonthIndex - i, 1)
    months.push(monthNames[date.getMonth()])

    const monthRecords = recordsData.value.filter(record => {
      const recordDate = new Date(record.consumptionDate)
      return recordDate.getMonth() === date.getMonth() &&
          recordDate.getFullYear() === date.getFullYear()
    })

    const monthTotal = monthRecords.reduce((sum, record) => sum + record.amount, 0)
    currentMonth.push(parseFloat(monthTotal.toFixed(2)))
  }

  return { months, currentMonth }
}
// 趋势图初始化
const initializeTrendChart = () => {
  if (!trendChart.value) return
  if (chartInstances.trend) chartInstances.trend.dispose()

  const trendData = generateTrendData()
  if (!trendData.dates.length) return

  chartInstances.trend = echarts.init(trendChart.value)
  chartInstances.trend.setOption({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: trendData.dates },
    yAxis: { type: 'value', axisLabel: { formatter: '¥{value}' } },
    series: [{
      data: trendData.amounts,
      type: 'line',
      smooth: true,
      itemStyle: { color: '#f56c6c' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(245, 108, 108, 0.6)' },
          { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
        ])
      }
    }]
  })
}
// 支付方式图初始化
const initializePaymentMethodChart = () => {
  if (!paymentMethodChart.value) return
  if (chartInstances.payment) chartInstances.payment.dispose()

  const paymentMethodData = generatePaymentMethodData()
  if (!paymentMethodData.length) return

  chartInstances.payment = echarts.init(paymentMethodChart.value)
  chartInstances.payment.setOption({
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: ¥{c} ({d}%)' },
    legend: { orient: 'vertical', right: 10, top: 'center' },
    series: [{
      name: '支付方式分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      data: paymentMethodData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
}
// 月度图初始化
const initializeMonthlyChart = () => {
  if (!monthlyChart.value) return
  if (chartInstances.monthly) chartInstances.monthly.dispose()

  const monthlyData = generateMonthlyData()
  if (!monthlyData.months.length) return

  chartInstances.monthly = echarts.init(monthlyChart.value)
  chartInstances.monthly.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['月度支出'], top: 30 },
    xAxis: { type: 'category', data: monthlyData.months },
    yAxis: { type: 'value', axisLabel: { formatter: '¥{value}' } },
    series: [{
      name: '月度支出',
      type: 'bar',
      data: monthlyData.currentMonth,
      itemStyle: { color: '#409eff' }
    }]
  })
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中')
}

// 组件生命周期
onMounted(() => {
  fetchAllData()
})

onUnmounted(() => {
  cleanupCharts()
})
</script>

<style scoped>
.category-detail-finance {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  overflow-y: scroll;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.page-header:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: #f56c6c;
  transition: transform 0.3s ease;
}

.page-header:hover .header-icon {
  transform: scale(1.1);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.no-data-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #909399;
  font-size: 16px;
  text-align: center;
  width: 100%;
}

.overview-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 0;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
  border-color: #409eff;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.stat-icon.total {
  background: #fef0f0;
  color: #f56c6c;
}

.stat-icon.count {
  background: #f6ffed;
  color: #67c23a;
}

.stat-icon.average {
  background: #fff7e6;
  color: #e6a23c;
}

.stat-icon.max {
  background: #f0f9ff;
  color: #409eff;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.table-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-text {
  font-weight: 600;
  color: #f56c6c;
}

.amount {
  color: #f56c6c;
  font-weight: 600;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-card :deep(.el-card__header) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-card__header) {
  background: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa !important;
  transition: background-color 0.2s ease;
}

:deep(.el-table_1_column_5 .cell) {
  display: flex;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
  background: white;
  border-radius: 4px;
}
</style>